package com.awesome.imagedemo.util

import java.io.*

/**
 * Author: zhangjingfang
 * Email:zhangjingfang@jeejio.com
 * Date: 2021/6/3 9:24
 * Description: 流工具类
 */
fun copy(inFile: File, outputStream: OutputStream): Boolean {
    if (!inFile.exists()) return false
    val inputStream: InputStream = try {
        FileInputStream(inFile)
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
        return false
    }
    return copy(inputStream, outputStream)
}

fun copy(inFile: File, outFile: File): Boolean {
    if (!inFile.exists()) return false
    val inputStream: InputStream = try {
        FileInputStream(inFile)
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
        return false
    }
    return copy(inputStream, outFile)
}

fun copy(inputStream: InputStream, outFile: File): Boolean {
    if (!outFile.exists()) {
        val fileParentDir = outFile.parentFile
        if (!fileParentDir.exists()) {
            if (!fileParentDir.mkdirs()) return false
        }
        try {
            if (!outFile.createNewFile()) return false
        } catch (e: IOException) {
            e.printStackTrace()
            return false
        }
    }
    val outputStream: OutputStream = try {
        FileOutputStream(outFile)
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
        return false
    }
    return copy(inputStream, outputStream)
}

fun copy(inputStream: InputStream, outputStream: OutputStream): Boolean {
    return try {
        val buffer = ByteArray(1024)
        var realLength: Int
        while (inputStream.read(buffer).also { realLength = it } > 0) {
            outputStream.write(buffer, 0, realLength)
        }
        true
    } catch (e: IOException) {
        e.printStackTrace()
        false
    } finally {
        close(inputStream)
        close(outputStream)
    }
}

fun close(vararg closeables: Closeable?) {
    if (closeables == null) return
    for (closeable in closeables) {
        if (closeable != null) {
            try {
                closeable.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}